package artid.com.arttogoa.view;

import java.util.ArrayList;
import java.util.List;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;

import artid.com.arttogoa.R;

public class LineCharView extends View {
    private int xori;//原点x坐标
    private int yori;//原点y坐标
    private int xinit;//第一个点x坐标  x轴左边的间距
    private int y_Top;//y轴上面的间距
    private int y_Buttom;//y轴下面的间距
    private int dotSize;//圆点大小
    private int minXinit;//在移动时，第一个点允许最小的x坐标
    private int maxXinit;//在移动时，第一个点允许允许最大的x坐标
    private int xylinecolor;//xy坐标轴颜色
    private int xylinewidth;//xy坐标轴大小
    private int xytextcolor;//xy坐标轴文字颜色
    private int xytextsize;//xy坐标轴文字大小
    private int linecolor;//折线的颜色
    private int y_interval;//Y坐标间的间隔
    private int x_interval;//X坐标间的间隔
    private int bgColor;//背景颜色
    private List<String> x_coords;//x坐标点的值
    private List<Integer> x_coord_values;//每个点状态值
    private List<Integer> y_coords;//y坐标点的值

    private int width;//控件宽度
    private int heigth;//控件高度
    private float textwidth;//y轴文字的宽度
    float startX = 0;//滑动时候，上一次手指的x坐标

    public LineCharView(Context context, AttributeSet attrs) {
        super(context, attrs);
        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.LineChar);
        xylinecolor = typedArray.getColor(R.styleable.LineChar_xylinecolor, Color.GRAY);
        xylinewidth = typedArray.getInt(R.styleable.LineChar_xylinewidth, 5);
        xytextcolor = typedArray.getColor(R.styleable.LineChar_xytextcolor, Color.BLACK);
        xytextsize = typedArray.getLayoutDimension(R.styleable.LineChar_xytextsize, 20);
        linecolor = typedArray.getColor(R.styleable.LineChar_linecolor, Color.GRAY);
        x_interval = typedArray.getLayoutDimension(R.styleable.LineChar_interval, 100);
        bgColor = typedArray.getColor(R.styleable.LineChar_bgcolor, Color.WHITE);
        typedArray.recycle();
        x_coords = new ArrayList<String>();
        x_coord_values = new ArrayList<Integer>();
    }

    public LineCharView(Context context) {
        super(context);
    }


//	@SuppressLint("DrawAllocation")
//	@Override
//	protected void onLayout(boolean changed, int left, int top, int right,
//			int bottom) {
//	
//		if(changed){
//		
//		super.onLayout(changed, left, top, right, bottom);
//	}
//

    @SuppressLint("DrawAllocation")
    @Override
    protected void onDraw(Canvas canvas) {
        drawX(canvas);
        drawXY(canvas);
        drawY(canvas);
    }


    //画坐标轴
    private void drawXY(Canvas canvas) {
        Paint paint = new Paint();
        paint.setColor(xylinecolor);
        paint.setStrokeWidth(xylinewidth);
    }

    //画Y轴坐标点
    private void drawY(Canvas canvas) {

        Paint paint = new Paint();
        paint.setStyle(Paint.Style.STROKE);
        paint.setColor(Color.GRAY);


        // 横向线
        for (int i = 0; (yori - i * y_interval) > 0; i++) {
            int startX = xinit - dotSize;
            int startY = yori - i * y_interval;
            int stopX = xori + this.x_coord_values.size() * x_interval;
            if (stopX < width) {
                stopX = width;
            }
            paint.setColor(linecolor);
            canvas.drawLine(startX, startY, stopX, startY, paint);

        }

        //将折线超出x轴坐标的部分截取掉
        paint.setStyle(Paint.Style.FILL);
        paint.setColor(bgColor);
        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_OVER));
        RectF rectF = new RectF(0, 0, xori, heigth);
        canvas.drawRect(rectF, paint);


        // Y轴上的字
        for (int i = 0; (yori - i * y_interval) > 0; i++) {
            if (i >= y_coords.size()) {
                break;
            }
            int startY = yori - i * y_interval;
            paint.setColor(xytextcolor);
            paint.setTextSize(xytextsize);
            canvas.drawText(String.valueOf(this.y_coords.get(i)), 10, startY, paint);
        }

    }


    //画X轴坐标点，折线，表情
    @SuppressLint("ResourceAsColor")
    private void drawX(Canvas canvas) {
        Paint x_coordPaint = new Paint();

        Log.i("xinit", xinit + "");
        x_coordPaint.setTextSize(xytextsize);
        x_coordPaint.setStyle(Paint.Style.FILL);
        Path path = new Path();
        //画坐标点
        for (int i = 0; i < x_coords.size(); i++) {
            int x = i * x_interval + xinit;
            if (i == 0) {
                path.moveTo(x, getYValue(x_coord_values.get(i)));
            } else {
                path.lineTo(x, getYValue(x_coord_values.get(i)));
            }


            String text = x_coords.get(i);
            x_coordPaint.setColor(xytextcolor);
            canvas.drawText(text, x - x_coordPaint.measureText(text) / 2, yori + xytextsize + xylinewidth * 2, x_coordPaint);
        }

        x_coordPaint.setStyle(Paint.Style.STROKE);
        x_coordPaint.setStrokeWidth(2f);

        x_coordPaint.setColor(linecolor);

        //画折线
        canvas.drawPath(path, x_coordPaint);


        //画圆点
        for (int i = 0; i < x_coords.size(); i++) {
            x_coordPaint.setStyle(Paint.Style.FILL);
            int x = i * x_interval + xinit;
            canvas.drawCircle(x, getYValue(x_coord_values.get(i)), dotSize, x_coordPaint);
        }


        //将折线超出x轴坐标的部分截取掉
        x_coordPaint.setStyle(Paint.Style.FILL);
        x_coordPaint.setColor(bgColor);
        x_coordPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_OVER));
        RectF rectF = new RectF(0, 0, xori, heigth);
        canvas.drawRect(rectF, x_coordPaint);

    }


    //得到y坐标
    private float getYValue(Integer value) {
        int y0 = 0;
        int y1 = 0;
        Log.i("zzzz", "y:" + value);
        try {
            y0 = y_coords.get(0);
            Log.i("zzzz", "y0" + y0);
            y1 = y_coords.get(1);
            Log.i("zzzz", "y1" + y1);
        } catch (Exception e) {
            Log.i("zzzz", "string changed is err");
            return 0;
        }
        try {
            Log.i("zzzz", "返回数据" + (yori - (value - y0) * y_interval / (y1 - y0)));
            return yori - ((value - y0) * y_interval / (y1 - y0));
        } catch (Exception e) {
            return 0;
        }
    }


    @Override
    public boolean onTouchEvent(MotionEvent event) {

        //如果不用滑动就可以展示所有数据，就不让滑动
        if (x_interval * x_coord_values.size() <= width - xori) {
            return false;
        }

        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                startX = event.getX();
                break;

            case MotionEvent.ACTION_MOVE:
                float dis = event.getX() - startX;
                startX = event.getX();
                if (xinit + dis > maxXinit) {
                    xinit = maxXinit;
                } else if (xinit + dis < minXinit) {
                    xinit = minXinit;
                } else {
                    xinit = (int) (xinit + dis);
                }
                invalidate();

                break;
        }
        return true;
    }


    public int getXori() {
        return xori;
    }


    public void setXori(int xori) {
        this.xori = xori;
    }


    public int getYori() {
        return yori;
    }


    public void setYori(int yori) {
        this.yori = yori;
    }


    public int getXinit() {
        return xinit;
    }


    public void setXinit(int xinit) {
        this.xinit = xinit;
    }


    public int getMinXinit() {
        return minXinit;
    }


    public void setMinXinit(int minXinit) {
        this.minXinit = minXinit;
    }


    public int getMaxXinit() {
        return maxXinit;
    }


    public void setMaxXinit(int maxXinit) {
        this.maxXinit = maxXinit;
    }


    public int getXylinecolor() {
        return xylinecolor;
    }


    public void setXylinecolor(int xylinecolor) {
        this.xylinecolor = xylinecolor;
    }


    public int getXylinewidth() {
        return xylinewidth;
    }


    public void setXylinewidth(int xylinewidth) {
        this.xylinewidth = xylinewidth;
    }


    public int getXytextcolor() {
        return xytextcolor;
    }


    public void setXytextcolor(int xytextcolor) {
        this.xytextcolor = xytextcolor;
    }


    public int getXytextsize() {
        return xytextsize;
    }


    public void setXytextsize(int xytextsize) {
        this.xytextsize = xytextsize;
    }


    public int getLinecolor() {
        return linecolor;
    }


    public void setLinecolor(int linecolor) {
        this.linecolor = linecolor;
    }


    public int getInterval() {
        return x_interval;
    }


    public void setInterval(int interval) {
        this.x_interval = interval;
    }


    public int getBgColor() {
        return bgColor;
    }


    public void setBgColor(int bgColor) {
        this.bgColor = bgColor;
    }


    public List<String> getX_coords() {
        return x_coords;
    }


    public List<Integer> getX_coord_values() {
        return x_coord_values;
    }


    /**
     * 设置坐标折线图值
     *
     * @param x_coords       横坐标坐标点
     * @param x_coord_values 每个点的值
     */
    public void setValue(List<String> x_coords, List<Integer> y_coords, List<Integer> x_coord_values) {
        if (x_coord_values.size() != x_coords.size()) {
            throw new IllegalArgumentException("坐标轴点和坐标轴点的值的个数必须一样!");
        }
        this.x_coord_values = x_coord_values;
        this.y_coords = y_coords;
        this.x_coords = x_coords;


        if (null == y_coords || null == x_coord_values || null == x_coords) {
            return;
        }

        width = getWidth();
        heigth = getHeight();
        Paint paint = new Paint();
        paint.setTextSize(xytextsize);
        textwidth = paint.measureText("A");
        xori = (int) (textwidth + 6 + 2 * xylinewidth);//6 为与y轴的间隔
        yori = heigth - xytextsize - 2 * xylinewidth - 3;
        if (y_coords.isEmpty()) {
            y_interval = 0;
        } else {
            y_interval = (this.getHeight() - y_Top - y_Buttom) / this.y_coords.size();
        }

        xinit = x_interval / 2 + xori;
        minXinit = width - xori - x_coords.size() * x_interval;
        maxXinit = xinit;
        y_Buttom = xytextsize - 2 * xylinewidth - 3;
        y_Top = xytextsize - 2 * xylinewidth - 3;
        dotSize = 6;
        setBackgroundColor(bgColor);

        Log.e("LineCharView", "width:" + width + '\n' +
                "heigth:" + heigth + '\n' +
                "textwidth:" + textwidth + '\n' +
                "xori:" + xori + '\n' +
                "yori:" + yori + '\n' +
                "y_interval:" + y_interval + '\n' +
                "xinit:" + xinit + '\n' +
                "minXinit:" + minXinit + '\n' +
                "maxXinit:" + maxXinit + '\n' +
                "y_Buttom:" + y_Buttom + '\n');


        invalidate();
    }


}
